package common_api

import (
	common_service "hft/Internal/Common/service"
	"hft/global"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 数据绑定的形式
const (
	_ int = iota //递增
	JSON
	QUERY
	XML
	YAML
	URI
)

// 规定成功与错误体
const (
	ERROR     = 100
	SUCCESS   = 200
	MISSLOGIN = -1
)

type Api struct {
	Context *gin.Context //路由上下文
	// Claims  *utils.CustomClaims //校验信息
	Orm    *gorm.DB //orm
	Errors error    //错误
}

// 获取上下文
func (a *Api) MakeContext(c *gin.Context) *Api {
	a.Context = c
	return a
}

// 是否需要绑定结构体
func (a *Api) Bind(d interface{}, bind int) *Api {
	var err error
	switch bind {
	case JSON:
		err = a.Context.ShouldBindJSON(d)
	case QUERY:
		err = a.Context.ShouldBindQuery(d)
	case XML:
		err = a.Context.ShouldBindXML(d)
	case YAML:
		err = a.Context.ShouldBindYAML(d)
	case URI:
		err = a.Context.ShouldBindUri(d)
	}
	a.Errors = err
	return a
}

// 选择ORM
func (a *Api) MakeOrm(funcs ...func(c *gin.Context) *gorm.DB) *Api {
	if len(funcs) == 1 {
		a.Orm = funcs[0](a.Context) //自定义函数设置orm
	} else {
		a.Orm = global.OC_DB
	}
	return a
}

// 选择Service
func (a *Api) MakeService(s *common_service.Service) *Api {
	s.Orm = a.Orm
	s.Error = a.Errors
	return a
}

// 响应体封装

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func Result(code int, data interface{}, msg string, c *gin.Context) {
	// 开始时间
	c.JSON(http.StatusOK, Response{
		code,
		msg,
		data,
	})
}

func (a *Api) Ok(c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
}

func (a *Api) OkWithMessage(message string, c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, message, c)
}

func (a *Api) OkWithData(data interface{}, c *gin.Context) {
	Result(SUCCESS, data, "查询成功", c)
}

func (a *Api) OkWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(SUCCESS, data, message, c)
}

func (a *Api) Fail(c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, "操作失败", c)
}

func (a *Api) FailWithMessage(message string, c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, message, c)
}

func (a *Api) FailWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(ERROR, data, message, c)
}

func (a *Api) MissLogin(message string, c *gin.Context) {
	Result(MISSLOGIN, map[string]interface{}{}, message, c)
}
